package com.yanqu.road.server.manger.activity.orewar;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.config.skill.SkillInfo;
import com.yanqu.road.entity.crossorewar.*;
import com.yanqu.road.entity.enums.*;
import com.yanqu.road.entity.orewar.UserOreData;
import com.yanqu.road.entity.orewar.UserOreRefuge;
import com.yanqu.road.entity.player.*;
import com.yanqu.road.entity.task.args.OreWarActivityUnionRiseRankArgs;
import com.yanqu.road.entity.task.args.UnionRiseRankArgs;
import com.yanqu.road.entity.union.UnionInfo;
import com.yanqu.road.logic.bussiness.player.UserBeautyBussiness;
import com.yanqu.road.logic.bussiness.player.UserOreWarBussiness;
import com.yanqu.road.logic.bussiness.player.UserPatronsBussiness;
import com.yanqu.road.logic.bussiness.servercenter.ActivityBussiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.logic.thread.ThreadTaskManger;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.cross.activity.CrossActivityProto;
import com.yanqu.road.pb.orewar.OreWarProto;
import com.yanqu.road.pb.player.PlayerProto;
import com.yanqu.road.pb.worldmessage.WorldMessageProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.player.BeautyModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.gameplayer.module.player.OreWarModule;
import com.yanqu.road.server.logic.battle.BattleManager;
import com.yanqu.road.server.logic.mail.MailManager;
import com.yanqu.road.server.manger.MultipleLanguageMgr;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.server.manger.config.SkillMgr;
import com.yanqu.road.server.manger.config.SystemOpenMgr;
import com.yanqu.road.server.manger.log.LogMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.player.WorldMessageMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.union.CrossUnionMgr;
import com.yanqu.road.server.manger.union.GameUnionActivityGroupMgr;
import com.yanqu.road.server.pb.OreWarPb;
import com.yanqu.road.server.pb.WorldMessagePb;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.RandomHelper;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.executor.GeneralTask;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.MessageFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
//本服用的
public class CrossOreWar {

	private Logger logger = LogManager.getLogger(CrossOreWar.class.getName());

	private final Object lockObj = new Object();

	private ActivityInfo activityInfo;

	//坑位的配置信息
	private Map<Integer, CrossOrePitInfo> crossOrePitInfoMap = new ConcurrentHashMap<>();

	//建筑的信息
	private Map<Integer, CrossOreStationInfo> crossOreStationMap = new ConcurrentHashMap<>();

	//用户坑位信息
//	private Map<Integer, CrossUserOrePit> crossUserOrePitMap = new ConcurrentHashMap<>();

	//用户被打的记录
	private Map<Long, List<CrossOreWarRecord>> crossOreWarRecordMap = new ConcurrentHashMap<>();

	//整个盐场的战斗记录
	private LinkedList<CrossOreWarNotice> crossOreWarNoticeList = new LinkedList<>();

	private RandomHelper random = new RandomHelper();

	private ThreadTaskManger threadTaskManger;

	private AtomicInteger actionId = new AtomicInteger(1);

	private int groupId;

	public int getGroupId() {
		return groupId;
	}

	public CrossOreWar(ActivityInfo acInfo, int groupId){
		activityInfo = acInfo;
		this.groupId = groupId;
//		reload();
		//启动立马请求同步数据
//		initData();
	}

	/**
	 * 本服的任务处理(定时同步异常数据，异常时候拉区完整跨服数据)
	 */
	public void timerTask(){
		long nowTimeMilli = System.currentTimeMillis();
		initData();
		systemRecall(nowTimeMilli);
	}

	public boolean init() {
		boolean reloadFlag = reload();
		if(reloadFlag){
			//启动立马请求同步数据
			initData();
		}
		return reloadFlag;
	}

	public boolean stop() {
		return false;
	}

	public boolean save() {
		return true;
	}

	public ActivityInfo getActivityInfo(){
		return activityInfo;
	}

	public boolean reload() {
		threadTaskManger = new ThreadTaskManger(4, "CrossOreWarTaskManger");

		crossOreStationMap = ActivityBussiness.getCrossOreWarStationInfoMap(activityInfo.getActivityId());
		if (crossOreStationMap.size() <= 0) {
			return false;
		}

		crossOrePitInfoMap = initCrossOrePitMap();
		if(crossOrePitInfoMap.size() <= 0){
			return false;
		}

		return true;
	}

	//跨服炸了或者出了什么问题重新请求获取跨服的所有坑位的信息
	public void reloadCrossPit(){
		initStationFlag = false;
		crossOrePitInfoMap = new ConcurrentHashMap<>();
		initData();
	}

	private boolean initStationFlag = false;
	public boolean isCrossStationSync(){
		return initStationFlag;
	}
	private boolean initNoticeFlag = false;
	public boolean isCrossNoticeSync(){
		return initNoticeFlag;
	}
	private boolean initRecordFlag = false;
	public boolean isCrossRecordSync(){
		return initRecordFlag;
	}

	private void initData(){
		if(!initStationFlag){
			//请求跨服用户坑位信息
			OreWarProto.CrossGetAllUserPitMsg.Builder reqMsg = OreWarProto.CrossGetAllUserPitMsg.newBuilder();
			reqMsg.setActivityId(activityInfo.getActivityId());
			reqMsg.setPitId(0);
			GamePlayerMgr.sendUnionActivityGroupPacket(CrossProtocol.C_CROSS_ORE_WAR_GET_STATION, reqMsg, 0, activityInfo.getActivityId(), groupId);
		}
		if(!initNoticeFlag){
			//请求跨服用户坑位信息
			OreWarProto.CrossGetAllNoticeMsg.Builder reqMsg = OreWarProto.CrossGetAllNoticeMsg.newBuilder();
			reqMsg.setActivityId(activityInfo.getActivityId());
			GamePlayerMgr.sendUnionActivityGroupPacket(CrossProtocol.C_CROSS_OREWAR_GET_ALL_NORICE, reqMsg, 0, activityInfo.getActivityId(), groupId);
		}
		if(!initRecordFlag){
			//请求跨服用户坑位信息
			OreWarProto.CrossGetAllRecordMsg.Builder reqMsg = OreWarProto.CrossGetAllRecordMsg.newBuilder();
			reqMsg.setActivityId(activityInfo.getActivityId());
			GamePlayerMgr.sendUnionActivityGroupPacket(CrossProtocol.C_CROSS_OREWAR_GET_ALL_RECORD, reqMsg, 0, activityInfo.getActivityId(), groupId);
		}
	}


	/**
	 * 按照ID规则生成矿坑地图信息
	 */
	private Map<Integer, CrossOrePitInfo> initCrossOrePitMap() {
		Map<Integer, CrossOrePitInfo> totalCrossOrePitInfoMap = new ConcurrentHashMap<>();
		int pitId = 1;
		for(CrossOreStationInfo stationInfo : getCrossOreStationMap().values()){
			for (int index = 0; index < stationInfo.getPitCount(); index++) {
				CrossOrePitInfo pitInfo = new CrossOrePitInfo();
				pitInfo.setActivityId(stationInfo.getActivityId());
				pitInfo.setName(stationInfo.getStationName());
				pitInfo.setStationId(stationInfo.getStationId());
				pitInfo.setPitId(pitId);
				pitInfo.setPitIndex(index + 1);
				pitInfo.setOutputSpeedAddition(stationInfo.getOutputSpeedAddition() + stationInfo.getAddOutputSpeedAddition() * (stationInfo.getPitCount() - index - 1));
				pitId++;
				totalCrossOrePitInfoMap.put(pitInfo.getPitId(), pitInfo);
			}
		}
		return totalCrossOrePitInfoMap;
	}

	@Deprecated
	public void sendCrossBlowoutMessage(){
		if(OreWarActivityMgr.getInTimeActivityInfo(activityInfo.getActivityId()) != null){

			WorldMessageProto.WorldMessageTempMsg.Builder msg = WorldMessageProto.WorldMessageTempMsg.newBuilder();
			msg.setActivityId(activityInfo.getActivityId());
			msg.setType(eMessageType.OreWarBlowout.getValue());

			msg.setContent("");
			msg.setSendTime(System.currentTimeMillis() / 1000);
			msg.setGroupId(groupId);

			CrossActivityProto.CrossActivityChatReqMsg.Builder reqMsg = CrossActivityProto.CrossActivityChatReqMsg.newBuilder();
			reqMsg.setActivityId(msg.getActivityId());
			reqMsg.setMsg(msg);
			reqMsg.setChannelId(ServerListMgr.getChannelId(GameServer.getInstance().getServerId()));
			reqMsg.setSyncChannel(false);

			GamePlayerMgr.sendUnionActivityGroupPacket(Protocol.C_CROSS_ACTIVITY_GROUP_CHAT, reqMsg,0, activityInfo.getActivityId(),groupId);


//			WorldMessageMgr.worldNotify(eMessageType.OreWarBlowout.getValue());
		}
	}

	public void crossNamingGetMessage(long userId,int stationId,String unionUid){
		UserInfo userInfo = UserMgr.getUserInfo(userId);
		if(null == userInfo)return;
		WorldMessageProto.WorldMessageTempMsg.Builder chatMsgGet = WorldMessagePb.parseWorldMessageTempMsg(userInfo,
				eMessageType.OreWarNamingGet.getValue(), eChatContentType.Common.getContentType(), getCrossOreStationName(stationId,userInfo.getLanguage()), System.currentTimeMillis(), 0, null);
		WorldMessageMgr.addWorldMessage(unionUid,chatMsgGet);
	}

	//userId 要有一个来获得语言，就用商会长的吧
	public void crossNamingLoseMessage(UserBaseInfo enemyBaseInfo,int stationId,String oldUnionUid){
		UnionInfo unionInfo = CrossUnionMgr.getUnionInfo(oldUnionUid);
		if(null == enemyBaseInfo || null == unionInfo)return;
		UserInfo userInfo = UserMgr.getUserInfo(unionInfo.getMasterUserId());
		if(null == userInfo)return;
		WorldMessageProto.WorldMessageTempMsg.Builder chatMsgLose = WorldMessagePb.parseWorldMessageTempMsg(userInfo,
				eMessageType.OreWarNamingLose.getValue(), eChatContentType.Common.getContentType(),
				WorldMessageMgr.encodeContent(enemyBaseInfo.getUnionName(),enemyBaseInfo.getNickName(),getCrossOreStationName(stationId,userInfo.getLanguage())),
				System.currentTimeMillis(), 0, null);
		WorldMessageMgr.addWorldMessage(oldUnionUid,chatMsgLose);
	}

	//冠名变化奖励
	public void crossNamingRewardMail(Map<Long,Map<Integer,String>> userPitRewardMap){
		for(long userId : userPitRewardMap.keySet()){
			Property allReward = new Property();
			Map<Integer,String> stationRewardMap = userPitRewardMap.get(userId);
			for(int stationId : stationRewardMap.keySet()){
				allReward.addProperty(PropertyHelper.parseStringToProperty(stationRewardMap.get(stationId)));
				// 冠名变化的玩家发奖励
				UserInfo namingUser = UserMgr.getUserInfo(userId);
				String mailTitle = MultipleLanguageMgr.getContent(MailManager.ACTIVITY_ORE_WAR_NAMING_CHANGE_TITLE, namingUser.getLanguage());
				String mailContent = StringUtils.format(MultipleLanguageMgr.getContent(MailManager.ACTIVITY_ORE_WAR_NAMING_CHANGE_CONTENT, namingUser.getLanguage())
						,getCrossOreStationName(stationId,namingUser.getLanguage()));
				MailManager.sendMail(userId, eMailType.DAILY.getValue(), stationRewardMap.get(stationId), mailContent, mailTitle);

				OreWarActivityMgr.conditionNotify(userId,eGamePlayerEventType.CrossOreWarAcCoinOutPut.getValue(),
						new OreWarActivityUnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_NORMAL, PropertyHelper.parseStringToProperty(stationRewardMap.get(stationId)).getCountByGoodsId(GameConfig.ACTIVITY_ORE_WAR_OUTPUT_GOODSID),
								namingUser.getUnionUid(), activityInfo.getActivityId()));
			}

		}
	}

	//井喷前发送奖励
	public void crossBlowoutRewardMail(Map<Long,Map<Integer,String>> userPitRewardMap){
		// 给每日自动撤回的玩家发送邮件和占领奖励
		for(long userId : userPitRewardMap.keySet()){
			Map<Integer,String> pitIdMap = userPitRewardMap.get(userId);
			for(int pitId : pitIdMap.keySet()){
				UserInfo recallUser = UserMgr.getUserInfo(userId);
				String mailTitle = MultipleLanguageMgr.getContent(MailManager.ACTIVITY_ORE_WAR_BLOWOUT_TITLE, recallUser.getLanguage());
				String mailContent = StringUtils.format(MultipleLanguageMgr.getContent(MailManager.ACTIVITY_ORE_WAR_BLOWOUT_CONTENT, recallUser.getLanguage())
						,getCrossOrePitName(pitId, recallUser.getLanguage()));
				MailManager.sendMail(userId, eMailType.DAILY.getValue(), pitIdMap.get(pitId), mailContent, mailTitle);

				OreWarActivityMgr.conditionNotify(userId,eGamePlayerEventType.CrossOreWarAcCoinOutPut.getValue(),
						new OreWarActivityUnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_NORMAL, PropertyHelper.parseStringToProperty(pitIdMap.get(pitId)).getCountByGoodsId(GameConfig.ACTIVITY_ORE_WAR_OUTPUT_GOODSID),
								recallUser.getUnionUid(), activityInfo.getChildType()));
			}

		}
	}
	//自己的避难所撤回
	public void systemRecall(long nowTimeMilli){
		List<Integer> acList = StringUtils.stringToIntegerList(activityInfo.getParam6(),"\\|");//活动开始在当天的分钟|活动结束在当天的分钟
		long toadyZeroTime = DateHelper.getZeroTimeStamp(nowTimeMilli)/1000;
		long startSec = acList.get(0) * 60 + toadyZeroTime;
		long endSec = acList.get(1) * 60 + toadyZeroTime;
		long nowTime = nowTimeMilli/1000;
		long targetTime = 0;//以这个作为基准时间来判断加入多少时间的需要撤回，考虑到更新服务器停服一天的情况导致过了休战期
		if(nowTime >= startSec){
			targetTime = startSec;
		}
		if(nowTime >= endSec){
			targetTime = endSec;
		}

		//全部跨服的撤回了再撤回本服的只占领了盐场的
		List<Long> userIdList = new ArrayList<>();
		for(CrossOreStationInfo crossOreStationInfo : crossOreStationMap.values()){
			if(crossOreStationInfo.getUserIdList().size() != 0){
				return;
			}
		}
		List<Long> userRefugeList = UserOreWarBussiness.getNeedRecallRefugeUserList(activityInfo.getActivityId(),targetTime);
		for(long userId : userRefugeList){
			if(!userIdList.contains(userId)){
				userIdList.add(userId);
			}
		}
		for(long userId : userIdList){
			if(userId != 0){
				Property refugeReward = crossSystemRecallRefuge(userId,nowTimeMilli);
				crossSystemRecallRewardMail(userId,refugeReward,new ArrayList<>());
				GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
				if(player != null){
					player.sendPacket(Protocol.U_ORE_WAR_MY_PIT_LIST, OreWarPb.parseMyOrePitListMsg(activityInfo.getActivityId(),new ArrayList<>(), false));
				}
			}
		}
	}

	//撤回玩家跨服盐场活动的避难所
	public Property crossSystemRecallRefuge(long userId,long recallTime){
		Property reward = new Property();
		// 给每日自动撤回的玩家发送邮件和占领奖励
		if(UserOreWarBussiness.isNeedRecallRefugeUser(activityInfo.getActivityId(),userId,recallTime)){
			reward = getRefugeSystemRecallAll(userId,recallTime);
		}
		return reward;
	}

	//获取系统撤回避难所的所有应该获得奖励
	private Property getRefugeSystemRecallAll(long userId,long nowTimeMilli) {
		Property reward = new Property();
		GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
		if(player != null){
			reward = player.getModule(OreWarModule.class).refugeRecallAll(activityInfo.getActivityId());
		}else{
			List<UserOreRefuge> needUpdate = new ArrayList<>();
			Map<Integer, UserOreRefuge> userOreRefugeMap = UserOreWarBussiness.getUserOreRefugeMap(userId,activityInfo.getActivityId());
			for(UserOreRefuge userOreRefuge : userOreRefugeMap.values()){
				if(userOreRefuge.getPatronsIdList() != null && userOreRefuge.getPatronsIdList().size() > 0){
					long nowTime = nowTimeMilli / 1000;
					long occupyTime = (nowTime - userOreRefuge.getLastGetRewardTime()) / 60;
					long lastGetRewardTime = userOreRefuge.getLastGetRewardTime();
					Map<Integer,UserPatrons> patronsMap = UserPatronsBussiness.getUserPatronsMap(userId,userOreRefuge.getPatronsIdList());
					BigInteger oreOutput = getRefugeOreOutput(userId,new ArrayList<>(patronsMap.values()), GameConfig.ACTIVITY_ORE_WAR_SQUARE_PROFIT).multiply(BigDecimal.valueOf(occupyTime)).toBigInteger();
					reward.addProperty(GameConfig.ACTIVITY_ORE_WAR_OUTPUT_GOODSID, oreOutput);
					updateOreRefugePatronsState(player,userOreRefuge, OreWarMgr.DISPATCH_ORE_NONE);
					userOreRefuge.setLastGetRewardTime(nowTime);
					userOreRefuge.setPatronsIdList(new ArrayList<>());
					needUpdate.add(userOreRefuge);
					//do-xx 跨服的撤回没有日志，且没有每个坑位的日志了，这里要处理，变成了跨服的撤回只有一条没有每个坑位的，避难所的撤回还是保留一条一条的
					Property thisProp = new Property();
					thisProp.addProperty(GameConfig.ACTIVITY_ORE_WAR_OUTPUT_GOODSID, oreOutput);
					LogMgr.addLogOreWarReward(userId, userOreRefuge.getActivityId(), userOreRefuge.getPitId(),PropertyHelper.parsePropertyToString(thisProp) ,
							nowTime - lastGetRewardTime, true, eLogMoneyType.CrossOreWarRefugeRecall.getValue());
				}

			}
			UserOreWarBussiness.updateUserOreRefugeList(needUpdate);
		}
		return reward;
	}

	//获取避难所的奖励
	public BigDecimal getRefugeOreOutput(long userId,List<UserPatrons> patronsList, int oreAddition){
		if(null == patronsList){
			return BigDecimal.ZERO;
		}
		double skillAddition;
		GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
		Map<Integer, UserBeauty> beautyMap;
		if(null != player){
			skillAddition = player.getModule(BeautyModule.class).getIdentitySkillAddition(eSkillType.MineOutput.getValue(), 0);
		}else {
			beautyMap = UserBeautyBussiness.getUserBeautyMap(userId);
			skillAddition = SkillMgr.getIdentitySkillAddition(beautyMap, eSkillType.MineOutput.getValue(), 0);
		}
		BigDecimal totalValue = BigDecimal.valueOf(oreAddition);
		double patronsSkillAddition = 0;
		for(UserPatrons userPatrons : patronsList){//计算天赋加成
			for(UserPatronsSkill patronsSkill : userPatrons.getSkillList()){
				if(patronsSkill.getType() != ePatronsSkillType.Talent.getValue()){
					continue;
				}
				SkillInfo skillInfo = SkillMgr.getSkillInfo(patronsSkill.getSkillId());
				if(skillInfo.getType() == eSkillType.MineWarAddOutput.getValue()){
					patronsSkillAddition += SkillMgr.getSkillAddition(skillInfo, patronsSkill.getSkillLv());
				}
			}
		}
		totalValue = totalValue.multiply(BigDecimal.valueOf((patronsSkillAddition + skillAddition) / 1000 + 1)).multiply(BigDecimal.valueOf(patronsList.size())).
				setScale(0, BigDecimal.ROUND_UP);
		return totalValue;
	}


	public void crossSystemRecallRewardMail(long userId,Property systemRecallReward,List<CrossUserOrePit> crossUserOrePitList){
		GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
		if(player != null){
			player.getModule(OreWarModule.class).syncOreRefuge(activityInfo.getActivityId());
			player.getModule(OreWarModule.class).clearOrePitPatronsState(activityInfo.getActivityId());
		}
		for(CrossUserOrePit crossUserOrePit : crossUserOrePitList){
			syncOldOnlineUserCrossOrePit(userId,crossUserOrePit);
		}
		// 给每日自动撤回的玩家发送邮件和占领奖励
		UserInfo recallUser = UserMgr.getUserInfo(userId);
		String mailTitle = MultipleLanguageMgr.getContent(MailManager.ACTIVITY_ORE_WAR_TIMEOVER_TITLE, recallUser.getLanguage());
		String mailContent = MultipleLanguageMgr.getContent(MailManager.ACTIVITY_ORE_WAR_TIMEOVER_CONTENT, recallUser.getLanguage());
		MailManager.sendMail(userId, eMailType.DAILY.getValue(), PropertyHelper.parsePropertyToString(systemRecallReward), mailContent, mailTitle);

		OreWarActivityMgr.conditionNotify(userId,eGamePlayerEventType.CrossOreWarAcCoinOutPut.getValue(),
				new OreWarActivityUnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_NORMAL, systemRecallReward.getCountByGoodsId(GameConfig.ACTIVITY_ORE_WAR_OUTPUT_GOODSID),
						recallUser.getUnionUid(), activityInfo.getActivityId()));

		LogMgr.addLogOreWarReward(userId, activityInfo.getActivityId(), 0, PropertyHelper.parsePropertyToString(systemRecallReward),
							0, false, eLogMoneyType.CrossOreWarSysTemRecallReward.getValue());
	}

	//同步跨服下发的跨服坑位信息,客服端会定时自己来拉取
	/*public void crossPitSync(List<CrossUserOrePit> crossUserOrePitList,boolean isAllSync){
		//是否是同步所有的坑位
		if(isAllSync){
			initUserPitFlag = isAllSync;
		}
		for(CrossUserOrePit crossUserOrePit : crossUserOrePitList){
			if(null == crossUserOrePitMap.get(crossUserOrePit.getPitId()) ||
					crossUserOrePit.getUpdateIndex() > crossUserOrePitMap.get(crossUserOrePit.getPitId()).getUpdateIndex()){
				CrossUserOrePit oldPit = crossUserOrePitMap.get(crossUserOrePit.getPitId());
				crossUserOrePitMap.put(crossUserOrePit.getPitId(),crossUserOrePit);
				syncOldOnlineUserCrossOrePit(oldPit,crossUserOrePit);
				syncOnlineUserCrossOrePit(crossUserOrePit);
			}
		}
	}*/


	public void crossPitStationSync(List<OreWarProto.CrossOreStationTempMsg> crossOreStationTempMsgList,boolean isAllSync){
		//是否是同步所有的坑位
		if(isAllSync){
			initStationFlag = true;
		}
		for(OreWarProto.CrossOreStationTempMsg crossOreStationTempMsg : crossOreStationTempMsgList){
			CrossOreStationInfo crossOreStationInfo = crossOreStationMap.get(crossOreStationTempMsg.getStationId());
			crossOreStationInfo.setOccupyCount(crossOreStationTempMsg.getOccupyCount());
			crossOreStationInfo.setBlowout(crossOreStationTempMsg.getIsBlowout());
			crossOreStationInfo.setServerId(crossOreStationTempMsg.getNameServerId());
			crossOreStationInfo.setUnionUid(crossOreStationTempMsg.getUnionUid());
			crossOreStationInfo.setUnionName(crossOreStationTempMsg.getUnionName());
			crossOreStationInfo.setUserIdList(crossOreStationTempMsg.getUserIdList());
		}
	}

	private void syncOnlineUserCrossOrePit(CrossUserOrePit crossUserOrePit){
		GamePlayer player = GamePlayerMgr.getOnlinePlayer(crossUserOrePit.getUserId());
		if(null != player){
			//同步自己占领的坑位信息给自己
			player.getModule(OreWarModule.class).syncCrossOrePit(crossUserOrePit, false);
		}
	}

	private void syncOldOnlineUserCrossOrePit(CrossUserOrePit oldPit,CrossUserOrePit newPit){
		if(oldPit == null)return;
		if(oldPit.getServerId() == GameServer.getInstance().getServerId()){
			GamePlayer player = GamePlayerMgr.getOnlinePlayer(oldPit.getUserId());
			if(null != player){
				//同步自己被占领的坑位信息给自己
				player.getModule(OreWarModule.class).syncCrossOrePit(newPit, true);
			}
		}
	}

	private void syncOldOnlineUserCrossOrePit(long userId,CrossUserOrePit newPit){
		GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
		if(null != player){
			//同步自己被占领的坑位信息给自己
			player.getModule(OreWarModule.class).syncCrossOrePit(newPit, true);
		}
	}

	//同步跨服下发的跨服坑位信息
	public void crossRecordSync(List<CrossOreWarRecord> crossOreWarRewardList,boolean isAllSync){
		if(isAllSync){
			initRecordFlag = isAllSync;
		}
		for(CrossOreWarRecord crossOreWarRecord : crossOreWarRewardList){
			synchronized (crossOreWarRecordMap) {
				if (!crossOreWarRecordMap.containsKey(crossOreWarRecord.getUserId())) {
					crossOreWarRecordMap.put(crossOreWarRecord.getUserId(), new ArrayList<>());
				}
				crossOreWarRecordMap.get(crossOreWarRecord.getUserId()).add(crossOreWarRecord);
			}
			GamePlayer player = GamePlayerMgr.getOnlinePlayer(crossOreWarRecord.getUserId());
			if(player != null){
				List<CrossOreWarRecord> syncList = new ArrayList<>();
				syncList.add(crossOreWarRecord);
				player.sendPacket(Protocol.U_ORE_WAR_RECORD_SYNC, OreWarPb.parseCrossOreWarRecordListMsg(syncList));
			}
		}
	}

	public void crossNoticeSync(List<CrossOreWarNotice> syncCrossOreWarNoticeList,boolean isAllSync){
		if(isAllSync){
			initNoticeFlag = isAllSync;
		}
		for(CrossOreWarNotice crossOreWarNotice : syncCrossOreWarNoticeList){
			crossOreWarNoticeList.add(crossOreWarNotice);
		}
	}

	//领取跨服奖励
	public void addCrossGetReward(GamePlayer player,Property occupyReward){
		player.getModule(CurrencyModule.class).addCurrency(occupyReward, eLogMoneyType.OreWar, eLogMoneyType.CrossOreWarGetOccupyReward);
		if(!StringUtils.isNullOrEmpty(PropertyHelper.parsePropertyToString(occupyReward))){//有领到收益
			//增加一次领取收益
			player.notifyListener(eGamePlayerEventType.MineWarGetRewardTimes.getValue(), 1);
			OreWarActivityMgr.conditionNotify(player.getUserId(),eGamePlayerEventType.CrossOreWarAcCoinOutPut.getValue(),
					new OreWarActivityUnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_NORMAL, occupyReward.getCountByGoodsId(GameConfig.ACTIVITY_ORE_WAR_OUTPUT_GOODSID),
							player.getUserInfo().getUnionUid(), activityInfo.getActivityId()));
			LogMgr.addLogOreWarReward(player.getUserId(), activityInfo.getActivityId(), 0, PropertyHelper.parsePropertyToString(occupyReward),
					0, false, eLogMoneyType.CrossOreWarGetOccupyReward.getValue());
		}
	}


	//撤回发放奖励给用户
	public void addCrossRecallReward(GamePlayer player,int pitId,long rewardValue,int rewardMin,List<Integer> patronIdList){
		updateOrePitPatronsState(player.getUserId(), patronIdList,pitId,OreWarMgr.DISPATCH_ORE_NONE);
		int goodsId = GameConfig.ACTIVITY_ORE_WAR_OUTPUT_GOODSID;
		Property occupyReward = new Property();
		occupyReward.setGood(goodsId,BigInteger.valueOf(rewardValue));
		player.getModule(CurrencyModule.class).addCurrency(occupyReward, eLogMoneyType.OreWar, eLogMoneyType.OreWarPitRecall);
		OreWarActivityMgr.conditionNotify(player.getUserId(),eGamePlayerEventType.CrossOreWarAcCoinOutPut.getValue(),
				new OreWarActivityUnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_NORMAL, occupyReward.getCountByGoodsId(GameConfig.ACTIVITY_ORE_WAR_OUTPUT_GOODSID),
						player.getUserInfo().getUnionUid(), activityInfo.getActivityId()));
		//do-xx 跨服的日志新增，不新增了，就这样吧
		LogMgr.addLogOreWarReward(player.getUserId(), activityInfo.getActivityId(), pitId, PropertyHelper.parsePropertyToString(occupyReward), rewardMin,
				false, eLogMoneyType.CrossOreWarPitRecall.getValue());
	}

	//校验下可以去跨服打金融战不
	public int checkCrossRobPit(GamePlayer player,int pitId,List<Integer> patronsIdList,long pitOwnerUserId){
		if(!SystemOpenMgr.systemOpen(player, eSystemId.OreWar.getValue())){
			return GameErrorCode.E_SYSTEM_NO_OPEN;
		}
		if(patronsIdList.size() > GameConfig.MINE_WAR_BATTLE_MAX_PATRONS_COUNT){
			return GameErrorCode.E_ORE_WAR_PATRONS_COUNT_OVER;
		}
		//检测矿坑是否存在
		CrossOrePitInfo pitInfo = crossOrePitInfoMap.get(pitId);
		if(null == pitInfo){
			return GameErrorCode.E_ORE_WAR_ORE_PIT_NO_FOUND;
		}
		//检测出战门客战斗次数，是否需要发费元宝
		int ret = player.getModule(OreWarModule.class).checkAndCostBattleTimes(patronsIdList,activityInfo.getActivityId());
		if(0 != ret){
			return ret;
		}

		int occupyCount = player.getModule(OreWarModule.class).getOccupyCount(activityInfo.getActivityId());
		if(occupyCount >= GameConfig.ACTIVITY_ORE_WAR_OCCUPY_LIMIT){
			return GameErrorCode.E_ORE_WAR_OCCUPY_LIMIT;
		}
		//消耗体力，不够返回错误码
		return player.getModule(OreWarModule.class).useHp(activityInfo.getActivityId());
	}


	//从跨服返回的战斗结果获得玩家的奖励,以及把对应的门客标记上战斗状态
	public void addCrossOreWarReward(GamePlayer player,String rewardStr,int pitId,List<Integer> patronIdList,CrossUserOrePit crossUserOrePit){
		syncOnlineUserCrossOrePit(crossUserOrePit);
		updateOrePitPatronsState(player.getUserId(), patronIdList,pitId,OreWarMgr.DISPATCH_ORE_PUBLIC);
		//收益入袋
		Property reward = PropertyHelper.parseStringToProperty(rewardStr);
		player.getModule(CurrencyModule.class).addCurrency(reward, eLogMoneyType.OreWar, eLogMoneyType.OreWarWinReward);
		OreWarActivityMgr.conditionNotify(player.getUserId(),eGamePlayerEventType.CrossOreWarAcCoinOutPut.getValue(),
				new OreWarActivityUnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_NORMAL, reward.getCountByGoodsId(GameConfig.ACTIVITY_ORE_WAR_OUTPUT_GOODSID),
						player.getUserInfo().getUnionUid(), activityInfo.getActivityId()));

		//do-xx 跨服的日志新增 ，不加了，告辞
		LogMgr.addLogOreWarReward(player.getUserId(), activityInfo.getActivityId(), pitId, PropertyHelper.parsePropertyToString(reward),
				GameConfig.MINE_WAR_VICTORY_REWARD, false, eLogMoneyType.CrossOreWarWinReward.getValue());

		//增加累计占领次数
		UserOreData userOreData = player.getModule(OreWarModule.class).getUserOreData();
		userOreData.setTotalRobTimes(userOreData.getTotalRobTimes() + 1);
		//成就、任务
		player.notifyListener(eGamePlayerEventType.MineWarRobTimes.getValue(), 1);
		player.notifyListener(eGamePlayerEventType.MineWarTotalRobTimes.getValue(), userOreData);

	}


	//玩家在跨服上被打下来后发送邮件奖励以及将他的人才从战斗状态上撤下来啊
	public void addCrossOreWarRewardMail(long userId,long attackerUserId,UserBaseInfo attackerInfo,String reward,int pitId,List<Integer> patronsIdList,CrossUserOrePit crossUserOrePit){
		syncOldOnlineUserCrossOrePit(userId,crossUserOrePit);
		updateOrePitPatronsState(userId, patronsIdList,pitId,OreWarMgr.DISPATCH_ORE_NONE);

		// 给失败的玩家发送邮件和占领奖励
		UserInfo loserUser = UserMgr.getUserInfo(userId);
		String mailTitle = MultipleLanguageMgr.getContent(MailManager.MINE_WAR_BE_ROB_TITLE, loserUser.getLanguage());
		String mailContent = StringUtils.format(MultipleLanguageMgr.getContent(MailManager.MINE_WAR_BE_ROB_CONTENT, loserUser.getLanguage()),
				getCrossOrePitName(pitId, loserUser.getLanguage()), attackerInfo.getNickName());
		Property enemyReward = PropertyHelper.parseStringToProperty(reward);
		MailManager.sendMail(userId, eMailType.DAILY.getValue(), PropertyHelper.parsePropertyToString(enemyReward), mailContent, mailTitle);

		if(enemyReward != null){
			//被打者领取奖励
			OreWarActivityMgr.conditionNotify(loserUser.getUserId(),eGamePlayerEventType.CrossOreWarAcCoinOutPut.getValue(),
					new OreWarActivityUnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_NORMAL, enemyReward.getCountByGoodsId(GameConfig.ACTIVITY_ORE_WAR_OUTPUT_GOODSID),
							loserUser.getUnionUid(), activityInfo.getActivityId()));
		}
	}


	//根据用户盐场坑位撤回玩家门客占领数据
	private void updateOrePitPatronsState(long userId,List<Integer> patronsIdList,int updatePitId,int dispatchOre){
		int activityId = activityInfo.getActivityId();
		int pitId = 0;
		if(dispatchOre > 0){
			pitId = updatePitId;
		}
		GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
		if(null != player){
			player.getModule(OreWarModule.class).updateOrePitPatronsState(patronsIdList, dispatchOre, activityId, pitId);
		}else {//通过修改数据库修改状态
			UserOreWarBussiness.updateUserOreWarPatronsData(userId, patronsIdList, dispatchOre, activityId, pitId);
		}
	}




	public OreWarProto.OreWarNoticeListMsg.Builder getCrossUserOreWarNotice(GamePlayer player){
		List<CrossOreWarNotice> cOreWarNoticeList = new ArrayList<>(crossOreWarNoticeList);
		List<CrossOreWarNotice> resCrossOreWarNoticeList = new ArrayList<>();
		for(CrossOreWarNotice crossOreWarNotice : cOreWarNoticeList){
			if(!StringUtils.isNullOrEmpty(crossOreWarNotice.getEnemyBaseInfo().getUnionUid()) &&
					crossOreWarNotice.getEnemyBaseInfo().getUnionUid().equals(player.getUserInfo().getUnionUid())){
				resCrossOreWarNoticeList.add(crossOreWarNotice);
			}else if(getCrossOreStationInfo(getCrossOrePitInfo(crossOreWarNotice.getPitId()).getStationId()).isNotice()){
				resCrossOreWarNoticeList.add(crossOreWarNotice);
			}
		}
		OreWarProto.OreWarNoticeListMsg.Builder msg = OreWarPb.parseCrossOreWarNoticeListMsg(resCrossOreWarNoticeList);
		return msg;
	}

	/**
	 * 获取矿战来访记录
	 */
	public List<CrossOreWarRecord> getCrossUserOreWarRecord(long userId){
		return crossOreWarRecordMap.get(userId);
	}

	//do-xx 更新了一个用戶的门客，要把队伍中的所有计算一遍传递给跨服,跨服同步下来同步到自己的服务器的时候再次计算一遍门客的技能信息，如果不一致就通知跨服更新
	//之前用的是crossUserOrePit里的门客，现在改用AAA
	public void patronsAbilityChange(GamePlayer player,int pitId, UserPatrons userPatrons) {
		List<UserPatrons> userPatronsList = player.getModule(OreWarModule.class).getPitUserPatronsList(activityInfo.getActivityId(),pitId);
		if(userPatronsList.size() == 0){
			return;
		}
		List<UserPatrons> newUserPatronsList = new ArrayList<>();
		boolean needUpdate = false;
		for(UserPatrons onePatrons : userPatronsList){
			if(onePatrons.getPatronsId() == userPatrons.getPatronsId()){
				needUpdate = true;
				newUserPatronsList.add(userPatrons);
			}else{
				newUserPatronsList.add(onePatrons);
			}
		}
		if(needUpdate){
			newUserPatronsList = BattleManager.getCloneSkillOreWarAddPatrons(newUserPatronsList);
			OreWarProto.CrossPatronsAbilityChangeSyncMsg.Builder syncMsg = OreWarPb.parseCrossPatronsAbilityChangeSyncMsg(player,activityInfo.getActivityId(),pitId,newUserPatronsList);
			int groupId = GameUnionActivityGroupMgr.getGroupId(activityInfo.getActivityId(), player.getUserId());
			GamePlayerMgr.sendUnionActivityGroupPacket(Protocol.C_CROSS_OREWAR_PATRONS_SYNC,syncMsg,player.getUserId(),activityInfo.getActivityId(),groupId);
		}
	}


	public Map<Integer, CrossOreStationInfo> getCrossOreStationMap() {
		return crossOreStationMap;
	}

	public CrossOreStationInfo getCrossOreStationInfo(int oreStationId){
		if(crossOreStationMap.containsKey(oreStationId)){
			return crossOreStationMap.get(oreStationId);
		}
		return null;
	}

	public CrossOrePitInfo getCrossOrePitInfo(int pitId) {
		if(crossOrePitInfoMap.containsKey(pitId)){
			return crossOrePitInfoMap.get(pitId);
		}
		return null;
	}

	public String getCrossOrePitName(int pitId, String language){
		CrossOrePitInfo pitInfo = getCrossOrePitInfo(pitId);
		if(null == pitInfo){
			return "";
		}
		CrossOreStationInfo stationInfo = getCrossOreStationInfo(pitInfo.getStationId());
		if(null == stationInfo){
			return "";
		}
		return StringUtils.format(MultipleLanguageMgr.getContent(stationInfo.getStationName(), language), stationInfo.getShowStationIndex()) + "#" + pitInfo.getPitIndex();
	}

	//不包含#多少的部分
	public String getCrossOreStationName(int stationId, String language){
		CrossOreStationInfo stationInfo = getCrossOreStationInfo(stationId);
		if(null == stationInfo){
			return "";
		}
		return StringUtils.format(MultipleLanguageMgr.getContent(stationInfo.getStationName(), language), stationInfo.getShowStationIndex());
	}

	//根据玩家广场坑位撤回玩家门客占领数据
	private static void updateOreRefugePatronsState(GamePlayer player, UserOreRefuge userOreRefuge, int dispatchOre){
		int activityId = userOreRefuge.getActivityId();
		int pitId = 0;
		if(dispatchOre > 0){
			pitId = userOreRefuge.getPitId();
		}
		if(null != player){
			player.getModule(OreWarModule.class).updateOrePitPatronsState(userOreRefuge.getPatronsIdList(), dispatchOre, activityId, pitId);
		}else {//通过修改数据库修改状态
			UserOreWarBussiness.updateUserOreWarPatronsData(userOreRefuge.getUserId(), userOreRefuge.getPatronsIdList(), dispatchOre, activityId, pitId);
		}
	}

	//任务执行
	public void addTask(GeneralTask task) {
		threadTaskManger.addTask(actionId.getAndIncrement(), task);
	}

	public void crossPatronsAbilityChange(GamePlayer player, Map<Integer, List<UserPatrons>> patronsMap) {
		if (patronsMap != null) {
			boolean needSend = false;
			OreWarProto.CrossPatronsListAbilityChangeSyncMsg.Builder syncMsg = OreWarProto.CrossPatronsListAbilityChangeSyncMsg.newBuilder();
			for (Map.Entry<Integer, List<UserPatrons>> entry : patronsMap.entrySet()) {
				Integer pitId = entry.getKey();
				List<UserPatrons> patronsList = entry.getValue();
				List<UserPatrons> userPatronsList = player.getModule(OreWarModule.class).getPitUserPatronsList(activityInfo.getActivityId(),pitId);
				if(userPatronsList.size() == 0){
					continue;
				}
				Map<Integer, UserPatrons> userPatronsMap = new HashMap<>();
				for (UserPatrons patrons : patronsList) {
					userPatronsMap.put(patrons.getPatronsId(), patrons);
				}
				List<UserPatrons> newUserPatronsList = new ArrayList<>();
				boolean needUpdate = false;
				for(UserPatrons onePatrons : userPatronsList){
					if(userPatronsMap.containsKey(onePatrons.getPatronsId())){
						needUpdate = true;
						newUserPatronsList.add(userPatronsMap.get(onePatrons.getPatronsId()));
					}else{
						newUserPatronsList.add(onePatrons);
					}
				}
				if(needUpdate){
					newUserPatronsList = BattleManager.getCloneSkillOreWarAddPatrons(newUserPatronsList);
					OreWarProto.CrossOreWarPatronsSyncMsg.Builder msg = OreWarPb.parseCrossOreWarPatronsSyncMsg(player, pitId, newUserPatronsList);
					syncMsg.addPatronsMsg(msg);
					needSend = true;

				}
			}
			if (needSend) {
				syncMsg.setActivityId(activityInfo.getActivityId());
				UserInfo userInfo = UserMgr.getUserInfo(player.getUserId());
				UserBaseInfo userBaseInfo = UserMgr.parseUserBaseInfo(userInfo, GameServer.getInstance().getServerId());
				PlayerProto.PlayerBaseTempMsg.Builder baseMsg = PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo);
				syncMsg.setPlayerBaseData(baseMsg);
				int groupId = GameUnionActivityGroupMgr.getGroupId(activityInfo, player.getUserId());
				GamePlayerMgr.sendUnionActivityGroupPacket(Protocol.C_CROSS_ORE_WAR_ALL_PATRONS_SYNC,syncMsg,player.getUserId(),activityInfo.getActivityId(),groupId);
			}
		}
	}
}
